
attribute vec3		va_Tangent1;
attribute vec3		va_Tangent2;

uniform vec3		viewOrigin;			// Passed in automatically
uniform vec3		lightOrigin;
uniform mat3		entityAxis;			// Passed in automatically
uniform vec2		bumpScale1;
uniform vec2		bumpScroll1;
uniform vec2		bumpScale2;
uniform vec2		bumpScroll2;
uniform float		deformMagnitude;

varying vec3		viewVector;
varying vec3		lightVector;
varying vec2		alphaTexCoord;
varying vec4		bumpTexCoord;
varying mat3		tangentToGlobal;
varying float		deformScale;


void main (void){

	vec4		deformVec;
	vec3		viewVec, lightVec;
	float		d1, d2;

	// Position invariant
	gl_Position = ftransform();

	// Compute the view vector in tangent space
	viewVec = viewOrigin - gl_Vertex.xyz;

	viewVector.x = dot(viewVec, va_Tangent1.xyz);
	viewVector.y = dot(viewVec, va_Tangent2.xyz);
	viewVector.z = dot(viewVec, gl_Normal.xyz);

	// Compute the light vector in tangent space
	lightVec = lightOrigin - gl_Vertex.xyz;

	lightVector.x = dot(lightVec, va_Tangent1.xyz);
	lightVector.y = dot(lightVec, va_Tangent2.xyz);
	lightVector.z = dot(lightVec, gl_Normal.xyz);

	// Copy the alpha map texcoord
	alphaTexCoord = gl_MultiTexCoord0.st;

	// Scale and scroll the bump map texcoords
	bumpTexCoord.st = gl_MultiTexCoord0.st * bumpScale1 + bumpScroll1;
	bumpTexCoord.pq = gl_MultiTexCoord0.st * bumpScale2 + bumpScroll2;

	// Compute the tangent-to-global transformation matrix
	tangentToGlobal[0].x = dot(va_Tangent1, entityAxis[0]);
	tangentToGlobal[1].x = dot(va_Tangent1, entityAxis[1]);
	tangentToGlobal[2].x = dot(va_Tangent1, entityAxis[2]);

	tangentToGlobal[0].y = dot(va_Tangent2, entityAxis[0]);
	tangentToGlobal[1].y = dot(va_Tangent2, entityAxis[1]);
	tangentToGlobal[2].y = dot(va_Tangent2, entityAxis[2]);

	tangentToGlobal[0].z = dot(gl_Normal, entityAxis[0]);
	tangentToGlobal[1].z = dot(gl_Normal, entityAxis[1]);
	tangentToGlobal[2].z = dot(gl_Normal, entityAxis[2]);

	// Compute the deform scale
	deformVec.x = 1.0;
	deformVec.y = 0.0;
	deformVec.z = dot(gl_Vertex, gl_ModelViewMatrixTranspose[2]);
	deformVec.w = 1.0;

	d1 = dot(deformVec, gl_ProjectionMatrixTranspose[0]);
	d2 = dot(deformVec, gl_ProjectionMatrixTranspose[3]);

	deformScale = min(d1 * (1.0 / max(d2, 1.0)), 0.02) * deformMagnitude;
}
